import time,re
import pandas as pd
import sys
import redis
import pickle
import logging
import hashlib
import configparser
import datetime
from sqlalchemy import create_engine, DateTime, String
import pymysql
import requests
import os
import pywencai
import akshare as ak
import pandas as pd
from datetime import datetime,timedelta
import traceback
pymysql.install_as_MySQLdb()

os.environ['PATH'] = '/home/chencan/node/bin:$PATH";'
log_format = "%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"  # 精确到秒
logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=date_format)

# 日志文件路径
log_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'application.log')

# 创建一个 handler，用于写入日志文件
file_handler = logging.FileHandler(log_file_path)
file_handler.setFormatter(logging.Formatter(log_format, date_format))
# 添加 handler 到 logger
logging.getLogger().addHandler(file_handler)

# 初始化配置解析器
config = configparser.ConfigParser()
current_dir = os.path.dirname(os.path.abspath(__file__))
config.read(current_dir+'/config.ini', encoding='utf-8')


# 获取Redis的配置信息
redis_host = config.get('Redis', 'host')
redis_port = config.getint('Redis', 'port')
redis_db = config.getint('Redis', 'db')
redis_password = config.get('Redis', 'password')
r = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password)

mysql_port = config.getint('mysql', 'port')
mysql_host = config.get('mysql', 'host')
mysql_db = config.get('mysql', 'db')
import urllib.parse
mysql_password = urllib.parse.quote(config.get('mysql', 'password'))
mysql_user = config.get('mysql', 'user')
db_url = f'mysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_db}'

engine = create_engine(db_url,pool_size=20,max_overflow=20,pool_recycle=60)



def get_next_trade_date(trade_date):
    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    # 筛选出所有晚于给定交易日的日期
    date_df = tool_trade_date_hist_sina_df[tool_trade_date_hist_sina_df["trade_date"] > pd.Timestamp(trade_date).date()]
    date_df = date_df.sort_values(by="trade_date", ascending=True)  # 按日期升序排序
    next_trade_date = date_df["trade_date"].values[0]  # 获取最接近给定日期的下一个交易日
    return next_trade_date.strftime("%Y%m%d")  # 格式化日期

# 定义获取前一个交易日的函数
def get_pre_trade_date(trade_date):
    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    date_df = tool_trade_date_hist_sina_df[tool_trade_date_hist_sina_df["trade_date"] < pd.Timestamp(trade_date).date()]
    date_df = date_df.sort_values(by="trade_date", ascending=False)
    pre_trade_date = date_df["trade_date"].values[0]
    return pre_trade_date.strftime("%Y%m%d")

def get_pre_trade_date_n(trade_date,n):
    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    date_df = tool_trade_date_hist_sina_df[tool_trade_date_hist_sina_df["trade_date"] < pd.Timestamp(trade_date).date()]
    date_df = date_df.sort_values(by="trade_date", ascending=False)
    pre_trade_date = date_df["trade_date"].values[n-1]
    return pre_trade_date.strftime("%Y%m%d")


#记录前一天的数据
def PanQianGeguReDu(query_date):
    pre_trade_date = get_pre_trade_date(query_date)
    next_trade_date = get_next_trade_date(query_date)
    last_year_date = get_pre_trade_date_n(query_date,200)

    question =f'''
        {query_date}个股热度
    '''

    logging.info(f"问句:{question}")
    df = pywencai.get(query=question,loop=True)
    df["股票代码"] = df["股票代码"].str[0:6]
    logging.info(f"获得的列名:{df.columns}")
    df = df.rename(columns={f'个股热度排名[{query_date}]': '个股热度排名'})
    df["日期"] = query_date
    df["个股热度"] = round((1- df["个股热度排名"]/len(df))*100,2)
    df=df[["股票代码","股票简称","个股热度","日期"]]

    df.colums=["code","name","redu","query_date"]
    r.set(f"stock_panqian_redu:{query_date}", pickle.dumps(df))
    r.expire("stock_panqian_redu:{query_date}",3600*8)
    df.to_sql("stock_panqian_redu",engine, if_exists='append', index=False)
    print(df)



if __name__ == '__main__':
    # 检查是否有命令行参数（除了脚本名称本身）
    if len(sys.argv) > 1:
        # 如果提供了命令行参数，使用第一个参数作为查询日期
        query_date = sys.argv[1]
    else:
        # 如果没有提供命令行参数，使用当前日期
        query_date = datetime.now().strftime('%Y%m%d')
    PanQianGeguReDu(query_date)



